package com.jh.pattern.singleton.register;

import com.jh.pattern.executor.ConcurrentExecutor;
import com.jh.pattern.factory.JavaCourse;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author JH_Wong
 * @projectName newforward
 * @title ContainerSingleton.java
 * @package com.jh.pattern.singleton.register
 * @description 容器单例
 * @date 2019-05-23 14:52
 */
public class ContainerSingleton {

    private ContainerSingleton() {
    }

    private final static ConcurrentHashMap<String, Object> IOC = new ConcurrentHashMap<>(16);

    public final static Object getBean(String className) {
        synchronized (IOC) {
            if (!IOC.containsKey(className)) {
                Object value = null;
                try {
                    value = Class.forName(className).newInstance();
                    IOC.put(className, value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return value;
            }
            return IOC.get(className);
        }
    }

    public static void main(String[] args) throws Exception {

        // 试用容器单例
        /*JavaCourse obj = (JavaCourse) ContainerSingleton.getBean("com.jh.pattern.factory.JavaCourse");
        obj.study();*/

        // 模拟线程并发
        ConcurrentExecutor.execute(() -> {
            Object obj = ContainerSingleton.getBean("com.jh.pattern.factory.JavaCourse");
            System.out.println(System.currentTimeMillis() + "" + obj);
        }, 10, 6);
    }

}
